package xipujewel.xipujewel.utils;

import net.esoar.modules.security.utils.Digests;
import net.esoar.modules.utils.Encodes;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xipujewel.xipujewel.entity.account.User;
import xipujewel.xipujewel.service.account.ShiroDbRealm.ShiroUser;

/**
 * @Title: UserUtil.java
 * @Package xipujewel.xipujewel.utils
 * @Description: 获取当前用户工具类
 * @Date 2013-9-25-下午10:24:50
 * @Author: qizai
 * @Version: V1.0.0
 */
public class UserUtil {
	private static Logger logger = LoggerFactory.getLogger(UserUtil.class);
	//
	public static final String HASH_ALGORITHM = "SHA-1";
	/** 迭代次数 */
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	public static void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));
		byte[] hashPassword = Digests.sha1(user.getPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}

	public static ShiroUser getUser() {
		Subject currentUser = getSubject();
		if (currentUser == null) {
			return null;
		}
		if (!(currentUser.getPrincipal() instanceof ShiroUser)) {
			return null;
		}
		ShiroUser principal = (ShiroUser) currentUser.getPrincipal();
		return principal;
	}

	/**
	 * 取出Shiro中的当前用户LoginName.默认为""
	 */
	public static String getCurrentUserLoginName() {
		ShiroUser user = getUser();
		if (null == user) {
			return "";
		}
		return user.getLoginName();
	}

	public static Subject getSubject() {
		Subject currentUser = null;
		try {
			currentUser = SecurityUtils.getSubject();
		} catch (UnavailableSecurityManagerException e) {
			logger.error("getSubject(): Attempt to use Shiro prior to initialization");
		}
		return currentUser;
	}

	public static void checkPermission(String permission) {
		Subject currentUser = getSubject();
		if (currentUser == null) {
			return;
		}
		try {
			currentUser.checkPermission(permission);
		} catch (org.apache.shiro.authz.UnauthenticatedException e) {
			logger.error("checkPermission(): Subject is anonymous");
		}
	}
}
